package com.oscar.ehome.base;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


import com.google.gson.Gson;
import com.google.gson.JsonParser;

/**
 * 响应对象基类 Created by xie on 2016/7/16.
 */
public class BaseBean<T> {
    /**
     * 成功状态 0:失败，1:成功
     */
    private int success;
    /**
     * 消息信息
     */
    private String message;
    /**
     * 消息对象
     */
    private T object;
    /**
     * 消息对象
     */
    private List<T> objects;
    /**
     * 时间戳
     */
    private Long timestamp;

    public int getSuccess() {
        return success;
    }

    public void setSuccess(int success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getObject() {
        return object;
    }

    public void setObject(T object) {
        this.object = object;
    }

    public List<T> getObjects() {
        return objects;
    }

    public void setObjects(List<T> objects) {
        this.objects = objects;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public static BaseBean fromJson(String json, Class clazz) {
        if (json == null || "".equals(json) || new JsonParser().parse(json).getAsJsonObject().get("object") != null) {
            if ("\"\"".equals(new JsonParser().parse(json).getAsJsonObject().get("object").toString())) {
                json = "";
            }
//            return new BaseBean<>();
        }
        return new Gson().fromJson(json, type(BaseBean.class, clazz));
    }

    private static ParameterizedType type(final Class raw, final Type... clazz) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return clazz;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }
}
